var fs = require('fs')
var dbpath = './students.json'
//获取所有学生
exports.findAll = function (callback) {
    fs.readFile(dbpath, function (err, data) {
        if(err){
            return callback(err)
        }
        callback(null,JSON.parse(data.toString()).students)
    })
}
//保存添加信息
exports.save=function(student,callback){
    fs.readFile(dbpath, function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data.toString()).students
        student.id = students[students.length - 1].id + 1
        students.push(student)
        var fileData = JSON.stringify({
            students: students
        })
        fs.writeFile(dbpath, fileData, function (err) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })

    })
}
//根据id查询单个学生
exports.findById = function (id, callback) {
    fs.readFile(dbpath, 'utf8', function (err, data) {
        if (err) {
            return callback(err)
        }
        var students = JSON.parse(data).students
        var ret = students.find(function (item) {
            return item.id == parseInt(id)
        })
        callback(null, ret)
    })
}
//更新学生
exports.update = function (student, callback) {
    fs.readFile(dbpath, 'utf-8', function (err, data) {
        if (err) {
            return callback(err)
        }
        // item.id==student.id是判断条件，符合返回该item
        var students = JSON.parse(data).students
        var stu = students.find(function (item) {
            return item.id == parseInt(student.id)//条件
        })
        for (var key in student) {
            stu[key] = student[key]

        }
        var fileData = JSON.stringify({
            students: students
        })
        fs.writeFile(dbpath, fileData, function (err) {
            if (err) {
                return callback(err)
            }
            callback(null)
        })

    })

}